# main.py - MCP服务入口文件
import os
import json
import uuid
import logging
import cv2
import numpy as np
from analysis_code import analyze_joined_video
from oss2 import Auth, Bucket

# 配置日志
logger = logging.getLogger("video-analysis")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

class VideoAnalysisService:
    """视频动作相似度分析MCP服务"""
    
    def __init__(self):
        """初始化服务"""
        logger.info("Initializing video analysis service...")
        
        # 1. 验证环境变量
        self._validate_environment()
        
        # 2. 配置OSS
        self._configure_oss()
        
        # 3. 初始化模型（预热）
        self._warmup_model()
        
        logger.info("Service initialized successfully!")
    
    def _validate_environment(self):
        """验证必要的环境变量"""
        required_vars = [
            'OSS_BUCKET_NAME', 
            'OSS_ENDPOINT',
            'OSS_ACCESS_KEY_ID',
            'OSS_ACCESS_KEY_SECRET'
        ]
        
        missing = [var for var in required_vars if not os.getenv(var)]
        if missing:
            error_msg = f"Missing required environment variables: {', '.join(missing)}"
            logger.error(error_msg)
            raise EnvironmentError(error_msg)
    
    def _configure_oss(self):
        """配置OSS连接"""
        self.bucket_name = os.getenv('OSS_BUCKET_NAME')
        self.endpoint = os.getenv('OSS_ENDPOINT')
        
        self.auth = Auth(
            os.getenv('OSS_ACCESS_KEY_ID'),
            os.getenv('OSS_ACCESS_KEY_SECRET')
        )
        self.bucket = Bucket(self.auth, self.endpoint, self.bucket_name)
        
        logger.info(f"OSS configured: {self.bucket_name}@{self.endpoint}")
    
    def _warmup_model(self):
        """预热模型（避免冷启动延迟）"""
        try:
            logger.info("Warming up YOLO model...")
            # 这里可以添加一个简单的测试分析
            # 例如：analyze_joined_video("test_video.mp4")
            logger.info("Model warmup completed")
        except Exception as e:
            logger.warning(f"Model warmup failed: {str(e)}")
            # 不中断服务，仅记录警告
    
    def preprocess(self, data):
        """
        预处理输入数据
        :param data: 原始请求数据
        :return: 处理后的数据
        """
        logger.info("Preprocessing request...")
        
        # 1. 检查请求格式
        if not isinstance(data, dict):
            raise ValueError("Request must be a JSON object")
        
        # 2. 获取视频数据
        if 'video' not in data:
            raise ValueError("Missing 'video' field in request")
        
        video_data = data['video']
        
        # 3. 验证视频数据
        if not isinstance(video_data, bytes) and not hasattr(video_data, 'read'):
            raise ValueError("'video' field must be binary data")
        
        logger.info("Preprocessing completed")
        return video_data
    
    def predict(self, video_data):
        """
        执行视频分析
        :param video_data: 预处理后的视频数据
        :return: 分析结果
        """
        logger.info("Starting video analysis...")
        
        # 1. 生成唯一任务ID
        task_id = f"task_{uuid.uuid4().hex[:8]}"
        logger.info(f"Task ID: {task_id}")
        
        # 2. 保存到临时文件
        video_path = f"/tmp/{task_id}.mp4"
        with open(video_path, 'wb') as f:
            f.write(video_data)
        
        try:
            # 3. 执行分析
            results = analyze_joined_video(video_path)
            
            # 4. 上传结果到OSS
            self._upload_results_to_oss(task_id, results)
            
            # 5. 构建响应
            response = self._build_response(task_id, results)
            
            logger.info(f"Analysis completed successfully: {task_id}")
            return response
            
        finally:
            # 6. 清理临时文件
            if os.path.exists(video_path):
                os.remove(video_path)
    
    def _upload_results_to_oss(self, task_id, results):
        """上传分析结果到OSS"""
        # 上传标记视频
        marked_video_key = f"results/{task_id}_marked.mp4"
        self.bucket.put_object_from_file(
            marked_video_key, 
            results["marked_video"]
        )
        
        # 上传JSON报告
        json_report_key = f"results/{task_id}_report.json"
        with open(results["json_report"], 'r') as f:
            self.bucket.put_object(
                json_report_key,
                f.read()
            )
        
        logger.info(f"Results uploaded to OSS: {task_id}")
    
    def _build_response(self, task_id, results):
        """构建响应数据"""
        # 构建OSS访问URL
        region = self.endpoint.replace('oss-', '').replace('.aliyuncs.com', '')
        base_url = f"https://{self.bucket_name}.{region}.aliyuncs.com"
        
        return {
            "task_id": task_id,
            "status": "completed",
            "results": {
                "marked_video": f"{base_url}/results/{task_id}_marked.mp4",
                "json_report": f"{base_url}/results/{task_id}_report.json",
                "excel_report": f"{base_url}/results/{task_id}_report.xlsx",
                "stats": {
                    "total_frames": results["stats"]["total_frames"],
                    "valid_frames": results["stats"]["valid_frames"],
                    "avg_similarity": results["stats"]["avg_similarity"]
                }
            }
        }
    
    def postprocess(self, result):
        """
        后处理结果
        :param result: 分析结果
        :return: 最终响应
        """
        logger.info("Postprocessing results...")
        
        # 可以在这里添加额外的后处理逻辑
        # 例如：格式化时间、添加业务逻辑等
        
        logger.info("Postprocessing completed")
        return result

# MCP服务要求的全局实例
service = VideoAnalysisService()
